package com.cheng.imagerelated.photoselecview;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.cheng.imagerelated.R;
import com.cheng.imagerelated.photoselecview.adpter.ImageAdapter;
import com.cheng.imagerelated.photoselecview.entity.Image;
import com.cheng.imagerelated.photoselecview.model.ImageModel;
import com.cheng.imagerelated.photoselecview.utils.StatusBarUtils;
import com.cheng.imagerelated.uTakePhoto.exception.TakeException;
import com.cheng.imagerelated.uTakePhoto.manager.ITakePhotoResult;
import com.cheng.imagerelated.uTakePhoto.manager.UTakePhoto;
import com.cheng.imagerelated.uTakePhoto.utils.TUriUtils;

import java.util.ArrayList;
import java.util.List;

public class ImageSelectorActivity extends Activity {
    // 选择最大的图片数
    private int mMaxCount;
    // 显示列数
    private int column;
    // 是否单选
    private boolean isSingle;
    // 是否显示拍照
    private boolean showCamera;
    // 已经选择的照片集合
    private ArrayList<String> mSelectedImages;
    // toolBar的颜色值
    private int toolBarColor;
    // bottomBar的颜色值
    private int bottomBarColor;
    // 状态栏的颜色值
    private int statusBarColor;
    // 状态栏字体是否为黑色
    private boolean isBack;


    private static final int PERMISSION_REQUEST_CODE = 0X00000011;

    // 表的三个小伙伴
    private RecyclerView mRecyclerView;
    private ImageAdapter adapter;
    private List<Image> imageData;

    // view
    private RelativeLayout rlToolBarColor;
    private TextView tvConfirm;
    private FrameLayout btnConfirm;
    private ImageView ivBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_selector);
        initIntent();
    }

    @Override
    protected void onStart() {
        super.onStart();
        checkPermissionAndLoadImages();
    }

    /**
     * 处理传送过来的数据
     */
    private void initIntent() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        assert bundle != null;
        mMaxCount = bundle.getInt(PhotoSelector.EXTRA_MAX_SELECTED_COUNT, PhotoSelector.DEFAULT_MAX_SELECTED_COUNT);
        column = bundle.getInt(PhotoSelector.EXTRA_GRID_COLUMN, PhotoSelector.DEFAULT_GRID_COLUMN);
        isSingle = bundle.getBoolean(PhotoSelector.EXTRA_SINGLE, false);
        showCamera = bundle.getBoolean(PhotoSelector.EXTRA_SHOW_CAMERA, true);
        mSelectedImages = bundle.getStringArrayList(PhotoSelector.EXTRA_SELECTED_IMAGES);
        toolBarColor = bundle.getInt(PhotoSelector.EXTRA_TOOLBARCOLOR, ContextCompat.getColor(this, R.color.blue));
        bottomBarColor = bundle.getInt(PhotoSelector.EXTRA_BOTTOMBARCOLOR, ContextCompat.getColor(this, R.color.blue));
        statusBarColor = bundle.getInt(PhotoSelector.EXTRA_STATUSBARCOLOR, ContextCompat.getColor(this, R.color.blue));
        isBack = bundle.getBoolean(PhotoSelector.EXTRA_STATUSBARTEXTCOLOR, false);
        // 状态栏设置
        StatusBarUtils.setColor(this, toolBarColor, isBack);

        initView();
    }

    private void initView() {
        rlToolBarColor = findViewById(R.id.rl_tool_bar_color);
        rlToolBarColor.setBackgroundColor(toolBarColor);
        tvConfirm = findViewById(R.id.tv_confirm);
        btnConfirm = findViewById(R.id.btn_confirm);
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 回传已选中得图片数据
                postbackmSelectedImages();
            }
        });
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 返回
                finish();
            }
        });
        initRecyclerView();

    }

    private void initRecyclerView() {
        mRecyclerView = findViewById(R.id.recycler_view);
        if (null == imageData) {
            imageData = new ArrayList<>();
        } else {
            imageData.clear();
        }
        if (null == adapter) {
            adapter = new ImageAdapter(btnConfirm, tvConfirm, this, showCamera, isSingle, mMaxCount);
        }
        adapter.setmListener(new ImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int content) {
                Toast.makeText(ImageSelectorActivity.this, "onItemClick", Toast.LENGTH_SHORT).show();
            }
        });
        adapter.setOnCameraClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 拍照
                camera();
            }
        });

        GridLayoutManager managerGrid = new GridLayoutManager(this, column);

        mRecyclerView.setLayoutManager(managerGrid);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(adapter);
    }

    /**
     * 拍照
     */
    private void camera() {
        UTakePhoto.with(this).openCamera(TUriUtils.getPhotoAlbum(this)).build(new ITakePhotoResult() {
            @Override
            public void takeSuccess(List<Uri> uriList) {

            }

            @Override
            public void takeFailure(TakeException ex) {

            }

            @Override
            public void takeCancel() {

            }
        });
    }

    /**
     * 回传选中得图片数据
     */
    private void postbackmSelectedImages() {
        if (null == adapter) {
            return;
        }
        ArrayList<Image> images = adapter.getmSelectImages();
        ArrayList<String> selectImage = new ArrayList<>();
        for (Image image : images) {
            selectImage.add(image.getPath());
        }
        if (selectImage.size() > 0) {
            Intent intent = new Intent();
            intent.putStringArrayListExtra(PhotoSelector.SELECT_RESULT, selectImage);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    /**
     * 刷新图片数据
     *
     * @param images
     */
    private void updateRecyclerData(ArrayList<Image> images) {
        if (null == imageData) {
            imageData = new ArrayList<>();
        } else {
            imageData.clear();
        }
        // 处理传过来得已选择图片
        setmSelectedImages(imageData, images);
        imageData.addAll(images);
        if (null == adapter) {
            adapter = new ImageAdapter(btnConfirm, tvConfirm, this, showCamera, isSingle, mMaxCount);
        }
        // 直接刷新会报错
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.setGridDataList(imageData);
            }
        });
    }

    private void setmSelectedImages(List<Image> images, ArrayList<Image> imageArrayList) {
        int count = null == mSelectedImages ? 0 : mSelectedImages.size();
        for (int i = 0; i < count; i++) {
            String path = mSelectedImages.get(i);

            int size = null == imageArrayList ? 0 : imageArrayList.size();
            for (int j = size - 1; j >= 0; j--) {
                Image image = imageArrayList.get(j);
                if (path.equals(image.getPath())) {
                    image.setSelect(true);
                    images.add(image);
                    imageArrayList.remove(image);
                }
            }

            int length = null == images ? 0 : images.size();
            boolean isPath = true;
            for (int j = 0; j < length; j++) {
                Image image = images.get(j);
                if (path.equals(image.getPath())) {
                    isPath = false;
                }
            }
            if (isPath) {
                String[] split = path.split("/");
                String imageName = "http";
                if (split.length > 1) {
                    imageName = split[split.length - 1];
                }
                Image image = new Image(path, getCurrentTimeMillis(), imageName);
                image.setSelect(true);
                images.add(image);
            }
        }
    }

    /**
     * 获取当前时间戳（10位）
     *
     * @return
     */
    private long getCurrentTimeMillis() {
        long time = System.currentTimeMillis() / 1000;
        return time;
    }

    /**
     * 检查权限并加载SD卡里的图片。
     */
    private void checkPermissionAndLoadImages() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            Toast.makeText(this, "没有图片", Toast.LENGTH_LONG).show();
            return;
        }
        int hasWriteContactsPermission = ContextCompat.checkSelfPermission(getApplication(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteContactsPermission == PackageManager.PERMISSION_GRANTED) {
            //有权限，加载图片。
            loadImageForSDCard();
        } else {
            //没有权限，申请权限。
            ActivityCompat.requestPermissions(ImageSelectorActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    }

    /**
     * 处理权限申请的回调。
     *
     * @param requestCode  requestCode
     * @param permissions  permissions
     * @param grantResults grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //允许权限，加载图片。
                loadImageForSDCard();
            } else {
                //拒绝权限，弹出提示框。
                showExceptionDialog();
            }
        }
    }

    /**
     * 发生没有权限等异常时，显示一个提示dialog.
     */
    private void showExceptionDialog() {
        new AlertDialog.Builder(this)
                .setCancelable(false)
                .setTitle("提示")
                .setMessage("该相册需要赋予访问存储的权限，请到“设置”>“应用”>“权限”中配置权限。")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        finish();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                startAppSettings();
            }
        }).show();
    }

    /**
     * 启动应用的设置
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }


    /**
     * 从SDCard加载图片。
     */
    private void loadImageForSDCard() {
        ImageModel.loadImageForSDCard(this, new ImageModel.DataCallback() {
            @Override
            public void onSuccess(ArrayList<Image> images) {
                updateRecyclerData(images);
                Log.d(TAG, "onSuccess: " + GsonUtils.toJson(images));
            }
        });
    }

    private static final String TAG = "ImageSelectorActivity";
}
